use std::sync::Arc;

use crate::{
    airport::{channel::Channel, tcp_channel::TCPChannel},
    application::Application,
};
use async_trait::async_trait;
use common::base::config::Config;
use tracing::debug;

use super::{get_max_message_size, net::SocketEventHandler};

pub struct XRPCEventHandler {
    max_message_size: u32,
}

impl XRPCEventHandler {
    pub fn new(config: &Box<Config>) -> Box<XRPCEventHandler> {
        let max_message_size = get_max_message_size(config);
        Box::new(XRPCEventHandler {
            max_message_size: max_message_size,
        })
    }
}
#[async_trait]
impl SocketEventHandler for XRPCEventHandler {
    fn max_message_size(&self) -> u32 {
        self.max_message_size
    }

    fn on_start(&self) {}

    fn on_stop(&self) {}

    async fn on_accept(&self, channel_id: i64) {
        debug!("创建链接 channel_id = {}", channel_id);

        let airport = Application::get_airport();

        let conn_id = airport
            .xprc_net
            .get_session_conn_id(channel_id)
            .await
            .unwrap();

        let channel_manager = airport.get_channel_manager();

        let tcp_channel: Arc<Box<dyn Channel>> =
            Arc::new(TCPChannel::new(airport, conn_id, channel_id, false));

        channel_manager.add_channel(tcp_channel, true).await;
    }

    async fn on_connect(&self, channel_id: i64) {
        let airport = Application::get_airport();

        let conn_id = airport
            .xprc_net
            .get_session_conn_id(channel_id)
            .await
            .unwrap();

        let channel_manager = airport.get_channel_manager();

        let tcp_channel: Arc<Box<dyn Channel>> =
            Arc::new(TCPChannel::new(airport, conn_id, channel_id, false));

        channel_manager.add_channel(tcp_channel, false).await;
    }

    /**
     *
     */
    async fn on_receive(&self, channel_id: i64, message: Vec<u8>) {
        let airport = Application::get_airport();

        let channel = airport.get_channel_manager().get_channel(channel_id).await;

        if channel.is_none() {
            return;
        }
        let channel = channel.unwrap();

        channel.message_in(message).await;
    }

    async fn on_disconnected(&self, channel_id: i64) {
        debug!("链接断开-------i64ConnId = {}", channel_id);

        let airport = Application::get_airport();

        airport
            .get_channel_manager()
            .remove_channel(channel_id)
            .await;
    }
}
